import logging
import os
import urllib
import webapp2

from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import memcache

from analyze import parse_dat

class Airfoil(db.Model):
    name = db.StringProperty(required=True) # long name
    points = db.TextProperty(required=True)

"""
class NewPage(webapp2.RequestHandler):
    def get(self):
        code = urllib.unquote(self.request.get('code'))

        self.response.out.write('<html><title>Airfoils for Laser-cutting</title><body>')
        self.response.out.write('<h1>Airfoils for Laser-cutting</h1>')
        self.response.out.write('''
            <form action="/new" method="post">
                <p>shortname</p> <textarea name="code"></textarea> <br/>
                <p>file data</p> <textarea name="content"></textarea> <br/>
                <input type="submit" value="switch">
            </form>
            ''')
        if code:
            airfoil = Airfoil.get_by_key_name(code)
            self.response.out.write('<h2>'+airfoil.name+'</h2>')
            for line in airfoil.points.split('\n'):
                self.response.out.write('<p>'+line.strip()+'</p>')
        self.response.out.write('</body></html>')
        """

"""
class NewPage(webapp2.RequestHandler):
    addition_date = db.DateTimeProperty(auto_now_add=True)
"""


def get_airfoils():
    q = Airfoil.all()
    af = q.fetch(10000)
    return af

def get_airfoil_names():
    # check cache
    af_names = memcache.get("airfoil_names")
    if af_names is not None:
        logging.info("Using memcache for airfoil names")
        return af_names
    else:
        logging.info("Using datastore for airfoil names")
        af_names = map(lambda x: x.name, get_airfoils())
        if not memcache.add("airfoil_names", af_names):
            logging.error("Failed to cache airfoil names")
        return af_names

class MainPage(webapp2.RequestHandler):
    def get(self):

        template_values = {
            'airfoils': get_airfoil_names()
        }

        error = self.request.get('error')
        if error:
            template_values['error'] = error
        path = os.path.join(os.path.dirname(__file__), 'templates', 'index.html')
        self.response.out.write(template.render(path, template_values))

class UploadPage(webapp2.RequestHandler):
    def get(self):
        self.response.out.write('''
            <form action="/upload" method="post">
                <p>filename</p> <textarea name="filename"></textarea> <br/>
                <p>data</p> <textarea name="data"></textarea> <br/>
                <input type="submit" value="switch">
            </form>
        ''')
    def post(self):
        # Create the file
        name = self.request.get('filename')
        data = self.request.get('data')
        if not name or not data:
            self.error(500)
            if not name:
                self.response.out.write("Missing name parameter")
            else:
                self.response.out.write("Missing data parameter")
            return

        q = Airfoil.all()
        q.filter('name =', name)
        found = q.get()
        if found:
            found.delete()
        # Open the file and write to it
        foil = Airfoil(name=name, points=data)
        foil.put()
        self.response.out.write("Success")
        # Evict cache
        logging.info("Flushing airfoil_names from cache")
        memcache.delete("airfoil_names")
        # Return with success

class DeletePage(webapp2.RequestHandler):
    def post(self):
        # Create the file
        name = self.request.get('filename')
        if not name:
            self.error(500)
            self.response.out.write("Missing name parameter")
            return
        q = Airfoil.all()
        q.filter('name =', name)
        found = q.get()
        if found:
            found.delete()

class SvgPage(webapp2.RequestHandler):
    def get(self):
        filename = self.request.get('filename')
        q = Airfoil.all()
        q.filter("name =", filename)
        af = q.get()
        if not af:
            error = urllib.urlencode({"error":"No such SVG"})
            self.redirect("/?%s" % error)
            return
        data = af.points
        cord_length = self.request.get("cord_length")
        laser_offset = self.request.get("laser_offset")
        bt_height = self.request.get("bt_height")

        if not cord_length:
            error = urllib.urlencode({"error":"Cord Length must be non-zero"})
            self.redirect("/?%s" % error)
            return
        else:
            cord_length = float(cord_length)

        # Laser offset or bt_height can be zero without issue

        if laser_offset:
            laser_offset = float(laser_offset)
        else:
            laser_offset = 0

        if not bt_height:
            bt_height = 0
        else:
            bt_height = float(bt_height)

        self.response.out.write(parse_dat(data, cord_length,
                                          laser_offset,
                                          bt_height))
        self.response.headers['Content-Type'] = "image/svg+xml"
        f, _ = os.path.splitext(filename)
        download_name = str(f) + "-" + str(cord_length) + "-" + str(laser_offset) + "-" + str(bt_height)+'.svg'
        self.response.headers['Content-Disposition'] = "attachment; filename=\"" + download_name + "\""

# cord length, laser offset, bottom template height
app = webapp2.WSGIApplication(
    [   ('/',   MainPage),
        ('/upload', UploadPage),
        ('/delete', DeletePage),
        ('/svg', SvgPage)    ],
    debug=True)
